import Time from "../../utils/time"

let tempFilePath = ""
const Player = require("../../utils/player");
var app = getApp();
var api = require('../../utils/interface.js');
var interval = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    contral: {
      isVideo: false,
      isPhoto: false,
      isMovie: false,
    },
    array: [{
      id: 1,
      name: '公开'
    }, {
      id: 2,
      name: '管理员和我'
    }, {
      id: 3,
      name: '仅我自己'
    }],
    phtotList: [],
    video: {},
    isVideoEnd: true,
    videoTime: "00:00",
    playAudio: {},
    player: {},
    isPlayer: false,

    groupId: 0,
    isMovie: false,
    movie: {},

    video_url: "",
    img_url: [],
    audio_url: '',
    text: '',
    position: '所在位置',
    index: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      groupId: options.id
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  deletePhoto: function(e) {
    console.log(e)
    let bind = e.currentTarget.dataset.bind,
      photoList = this.data.phtotList,
      contral = this.data.contral
    photoList.splice(bind, 1)
    console.log(photoList)
    if (photoList.length == 0) {
      console.log("长度为0")
      contral.isPhoto = false
    }
    this.setData({
      phtotList: photoList,
      contral: contral
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },
  //获取音频
  getVideo: function() {
    let that = this,
      contral = that.data.contral,
      video = that.data.video;
    video = wx.getRecorderManager()
    contral.isVideo = true
    video.duration = 60000 * 3
    // video.format ="mp3";
    video.start({format:"mp3"})
    var i = 0;
    this.initvideoTime();
    console.log("ahhh")
    this.setData({
      video: video,
      contral: contral
    })
    console.log(this.data)
  },
  //停止音频
  stopVideo: function() {
    let that = this,
      video = that.data.video,
      isVideoEnd = that.data.isVideoEnd
    isVideoEnd = false
    video.stop();
    clearInterval(interval);
    console.log(video);
    video.onStop((data) => {
      console.log(data)
      tempFilePath = data.tempFilePath
      wx.saveFile({
        tempFilePath: data.tempFilePath,
        success: res => {
          video.src = res.savedFilePath
          console.log(res);
          that.setData({
            isVideoEnd: isVideoEnd,
            video: video
          });
          //上传附件
          wx.uploadFile({
            url: api.wxapp.UploadFiles,
            filePath: res.savedFilePath,
            name: 'filename',
            success: function(res) {
              console.log(res + "_aaaaaaaaaa");
              var json = JSON.parse(res.data);
              if (json.code == 1) {
                that.setData({
                  audio_url: json.data.FileWebPath[0]
                });
              }
            }
          });
        }
      })
    })
  },

  //初始化音频
  initvideoTime: function() {
    let that = this,
      videoTime = that.data.videoTime,
      time = new Time,
      index = 0;
    interval = setInterval(function() {
      index++
      videoTime = time.secondConvertMinute(index)
      let isVideoEnd = that.data.isVideoEnd;
      that.setData({
        videoTime: videoTime
      })
      console.log(isVideoEnd)
      if (index == 60 || !isVideoEnd) {
        clearInterval(interval)
      }
    }, 1000)
  },
  //获取选中图片
  getPhoto: function(e) {
    let that = this,
      phtotList = that.data.phtotList,
      contral = that.data.contral;
    console.log("ahh")
    wx.chooseImage({
      sizeType: ["isVideoEnd"],
      count: 9,
      success: res => {
        console.log(res)
        contral.isPhoto = true;
        that.setData({
          phtotList: res.tempFilePaths,
          contral: contral
        })
        // console.log(res.tempFilePaths)
      }
    });
  },
  //视频
  getMovie: function() {
    let that = this,
      movie = that.data.movie,
      isMove = that.data.isMovie;
    wx.chooseVideo({
      maxDuration: 15,
      sourceType: ['album', 'camera'],
      success: data => {
        console.log(data);
        wx.uploadFile({
          url: api.wxapp.UploadFiles,
          filePath: data.tempFilePath,
          name: 'filename',
          success: function(res) {
            var json = JSON.parse(res.data);
            console.log(json);
            if (json.code == 1) {
              that.setData({
                video_url: json.data.FileWebPath[0],
                video_Imgurl: json.data.VideoImgUrl,
                isMovie: true
              });
            }
          }
        });
      }
    });
  },
  playAudio: function() {
    let that = this,
      video = that.data.video,
      isPlayer = that.data.isPlayer,
      player = wx.getBackgroundAudioManager(),
      src = video.src;
    player.src = src
    player.play();
    console.log(1);
    console.log(video.src)
    player.onPlay(function() {
      console.log("播放")
    })
    player.onError(function(data) {
      console.log(data)
      console.log("chucuo")
    })
    if (isPlayer) {
      player.stop()
    }
    isPlayer = !isPlayer
    that.setData({
      isPlayer: isPlayer,
      player: player
    });
  },
  //动态绑定文本
  bingtext: function(e) {
    this.setData({
      text: e.detail.value
    });
  },
  //删除音频
  deleteAudio: function() {
    console.log("ahhh")
    let that = this,
      player = that.data.player,
      isVideoEnd = that.data.isVideoEnd,
      contral = that.data.contral
    contral.isVideo = false
    isVideoEnd = true
    // player.stop()
    this.setData({
      player: player,
      contral: contral,
      isVideoEnd: isVideoEnd,
      audio_url: "",
      videoTime: ''
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  playAudio: function() {
    let that = this,
      video = that.data.video,
      isPlayer = that.data.isPlayer,
      player = wx.getBackgroundAudioManager(),
      src = video.src;
    player.src = src
    player.play();
    console.log(1);
    console.log(video.src)
    player.onPlay(function() {
      console.log("播放")
    })
    player.onError(function(data) {
      console.log(data)
      console.log("chucuo")
    })
    if (isPlayer) {
      player.stop()
    }
    isPlayer = !isPlayer
    that.setData({
      isPlayer: isPlayer,
      player: player
    });
  },
  //动态绑定文本
  bingtext: function(e) {
    this.setData({
      text: e.detail.value
    });
  },
  //删除音频
  deleteAudio: function() {
    console.log("ahhh")
    let that = this,
      player = that.data.player,
      isVideoEnd = that.data.isVideoEnd,
      contral = that.data.contral
    contral.isVideo = false
    isVideoEnd = true
    // player.stop()
    this.setData({
      player: player,
      contral: contral,
      isVideoEnd: isVideoEnd,
      audio_url: ''
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
  deleteMovie: function() {
    let contral = this.data.contral
    contral.isMovie = false
    console.log("ahhh")
    this.setData({
      contral: contral,
      isMovie: false,
      video_url: ''
    })
    console.log(this.data)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {},

  //打开所在位置
  bindlocation: function() {
    var that = this;
    wx.getSetting({
      success: function(res) {
        console.log(res);
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success(r) {
              console.log(r);
              wx.chooseLocation({
                success: function(xx) {
                  console.log(xx);
                  if (xx.address != '' && xx.address != undefined) {
                    that.setData({
                      position: xx.address
                    });
                  }

                }
              })
            }
          })
        } else {
          //打开地图选择
          wx.chooseLocation({
            success: function(xx) {
              console.log(xx);
              if (xx.address != '' && xx.address != undefined) {
                that.setData({
                  position: xx.address
                });
              }
            }
          });
        }
      }
    })
  },
  uploadimg: function() { //这里触发图片上传的方法
    var that = this;
    var pics = that.data.phtotList;
    wx.showLoading();
    app.uploadimg({
      path: pics,
      com: function(res) {
        console.log(res);
        var img = "";
        for (var i = 0; i < res.imgs.length; i++) {
          img += res.imgs[i] + "|"
        }
        img = img.length <= 0 ? "" : img.substring(0, img.length - 1);
        var param = {
          groupId: that.data.groupId,
          text: that.data.text,
          image: img,
          radio: that.data.audio_url,
          video: that.data.video_url,
          position: that.data.position,
          power: that.data.array[that.data.index].id,
          radioTime: that.data.videoTime,
          videoFaceImage: that.data.video_Imgurl
       
        };
        app.Post(api.wxapp.clock_detail_create, param, function(res) {
          wx.hideLoading();
          if (res.code == 1) {
            wx.showToast({
              title: '获得10个积分！',
              icon: 'success',
              duration: 2000,
              success: function() {
                setTimeout(function() {
                  wx.redirectTo({
                    url: '../fenxiang/fenxiang?id=' + res.data.groupId,
                  })
                }, 1000)
              }
            });
          } else {
            app.WxAlert(res.msg);
          }
        });
      }
    });
  },
  //发表
  bindsub: function() {
    var that = this;
    if (that.data.phtotList.length > 0) {
      this.uploadimg();
    } else {
      var param = {
        groupId: that.data.groupId,
        text: that.data.text,
        image: "",
        radio: that.data.audio_url,
        video: that.data.video_url,
        position: that.data.position,
        power: that.data.array[that.data.index].id,
        radioTime: that.data.videoTime,
        videoFaceImage: that.data.video_Imgurl
      };
      wx.showLoading();
      app.Post(api.wxapp.clock_detail_create, param, function(res) {
        wx.hideLoading();
        if (res.code == 1) {
          wx.showToast({
            title: '获得10个积分！',
            icon: 'success',
            duration: 2000,
            success: function() {
              setTimeout(function() {
                wx.redirectTo({
                  url: '../fenxiang/fenxiang?id=' + res.data.groupId,
                })

              }, 1000)

            }
          });
        } else {
          app.WxAlert(res.msg);
        }
      });
    }
  },
  //选择器
  bindPickerChange: function(e) {
    var that = this;
    that.setData({
      index: e.detail.value
    });
  },
  bindcancel: function() {
    wx.navigateBack({
      delta: 1
    })
  },
    onShareAppMessage: function () {
        return {
            title: '测试分享',
            path: '/page/index/index'
        }
    }
})